#include "kernel_operator.h"
#include "l1lossgrad_custom_tiling.h"
constexpr int32_t BUFFER_NUM = 2; // tensor num for each queues

class KernelL1LossGrad {
public:
    __aicore__ inline KernelL1LossGrad() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z,GM_ADDR s,GM_ADDR u,uint32_t reduction,int32_t totalLength, uint32_t tileNum)
    {
        this->reduction = static_cast<uint32_t>(reduction);
        sum=0.0;
        this->totalLength=totalLength;
        this->blockLength = totalLength / AscendC::GetBlockNum();
        this->tileNum = tileNum;
        this->tileLength = this->blockLength / tileNum / BUFFER_NUM;
        xGm.SetGlobalBuffer((__gm__ float *)x + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        yGm.SetGlobalBuffer((__gm__ float *)y + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        uGm.SetGlobalBuffer((__gm__ float *)u + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);

        zGm.SetGlobalBuffer((__gm__ float *)z + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        sGm.SetGlobalBuffer((__gm__ float *)s , this->tileLength);

        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(inQueueU, BUFFER_NUM, this->tileLength * sizeof(float));

        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(outQueueS, BUFFER_NUM, this->tileLength * sizeof(float));

        pipe.InitBuffer(tmpBuf0, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuf1, this->tileLength * sizeof(uint8_t));
        pipe.InitBuffer(tmpBuf2, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuf3, this->tileLength * sizeof(float));
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
        AscendC::LocalTensor<float> yLocal = inQueueY.AllocTensor<float>();
        AscendC::LocalTensor<float> uLocal = inQueueU.AllocTensor<float>();

        AscendC::DataCopy(xLocal, xGm[progress * this->tileLength], this->tileLength);
        AscendC::DataCopy(yLocal, yGm[progress * this->tileLength], this->tileLength);
        AscendC::DataCopy(uLocal, uGm[progress * this->tileLength], this->tileLength);

        inQueueX.EnQue(xLocal);
        inQueueY.EnQue(yLocal);
        inQueueU.EnQue(uLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        AscendC::LocalTensor<float> yLocal = inQueueY.DeQue<float>();
        AscendC::LocalTensor<float> uLocal = inQueueU.DeQue<float>();
        AscendC::LocalTensor<float> zLocal = outQueueZ.AllocTensor<float>();
        AscendC::LocalTensor<float> sLocal = outQueueS.AllocTensor<float>();

        AscendC::LocalTensor<float> tmpTensor0 = tmpBuf0.Get<float>();
        AscendC::Duplicate<float>(tmpTensor0, 1, this->tileLength);
        AscendC::LocalTensor<uint8_t> tmpTensor1 = tmpBuf1.Get<uint8_t>();
        AscendC::LocalTensor<float> tmpTensor2 = tmpBuf2.Get<float>();
        AscendC::LocalTensor<float> tmpTensor3 = tmpBuf3.Get<float>();


        if(reduction == 0){//none
            AscendC::Sub(zLocal, xLocal, yLocal, this->tileLength);
            AscendC::DumpTensor(zLocal,1,16);
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::EQ, this->tileLength);
            uint64_t mask0 = 256/sizeof(float);
            int repeat0 = this->tileLength/mask0;
            AscendC::BinaryRepeatParams repeatParams0 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor2, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask0, repeat0, repeatParams0);

            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::GT, this->tileLength);
            uint64_t mask1 = 256/sizeof(float);
            int repeat1 = this->tileLength/mask1;
            AscendC::BinaryRepeatParams repeatParams1 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask1, repeat1, repeatParams1);
            AscendC::Add(tmpTensor2, tmpTensor3, tmpTensor2, this->tileLength);

            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::LE, this->tileLength);
            uint64_t mask2 = 256/sizeof(float);
            int repeat2 = this->tileLength/mask2;
            AscendC::BinaryRepeatParams repeatParams2 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask2, repeat2, repeatParams2);
            AscendC::Muls(tmpTensor3, tmpTensor3, static_cast<float>(-1.0), this->tileLength);
            AscendC::Add(zLocal, tmpTensor3, tmpTensor2, this->tileLength);
            AscendC::DumpTensor(zLocal,2,16);
            AscendC::Mul(zLocal, zLocal, uLocal, this->tileLength);

        }else if(reduction == 1){//sum
            AscendC::Sub(zLocal, xLocal, yLocal, this->tileLength);
            AscendC::DumpTensor(zLocal,1,16);
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::EQ, this->tileLength);
            uint64_t mask0 = 256/sizeof(float);
            int repeat0 = this->tileLength/mask0;
            AscendC::BinaryRepeatParams repeatParams0 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor2, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask0, repeat0, repeatParams0);

            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::GT, this->tileLength);
            uint64_t mask1 = 256/sizeof(float);
            int repeat1 = this->tileLength/mask1;
            AscendC::BinaryRepeatParams repeatParams1 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask1, repeat1, repeatParams1);
            AscendC::Add(tmpTensor2, tmpTensor3, tmpTensor2, this->tileLength);

            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::LE, this->tileLength);
            uint64_t mask2 = 256/sizeof(float);
            int repeat2 = this->tileLength/mask2;
            AscendC::BinaryRepeatParams repeatParams2 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask2, repeat2, repeatParams2);
            AscendC::Muls(tmpTensor3, tmpTensor3, static_cast<float>(-1.0), this->tileLength);
            AscendC::Add(zLocal, tmpTensor3, tmpTensor2, this->tileLength);
            AscendC::DumpTensor(zLocal,2,16);
            AscendC::Duplicate<float>(uLocal, static_cast<float>(1.0), this->tileLength);
            AscendC::Mul(zLocal, zLocal, uLocal, this->tileLength);

        }else if(reduction == 2) {//mean
            AscendC::Sub(zLocal, xLocal, yLocal, this->tileLength);
            AscendC::DumpTensor(zLocal,1,16);
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::EQ, this->tileLength);
            uint64_t mask0 = 256/sizeof(float);
            int repeat0 = this->tileLength/mask0;
            AscendC::BinaryRepeatParams repeatParams0 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor2, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask0, repeat0, repeatParams0);

            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::GT, this->tileLength);
            uint64_t mask1 = 256/sizeof(float);
            int repeat1 = this->tileLength/mask1;
            AscendC::BinaryRepeatParams repeatParams1 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask1, repeat1, repeatParams1);
            AscendC::Add(tmpTensor2, tmpTensor3, tmpTensor2, this->tileLength);

            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::LE, this->tileLength);
            uint64_t mask2 = 256/sizeof(float);
            int repeat2 = this->tileLength/mask2;
            AscendC::BinaryRepeatParams repeatParams2 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask2, repeat2, repeatParams2);
            AscendC::Muls(tmpTensor3, tmpTensor3, static_cast<float>(-1.0), this->tileLength);
            AscendC::Add(zLocal, tmpTensor3, tmpTensor2, this->tileLength);
            AscendC::Duplicate<float>(uLocal, static_cast<float>(1.0), this->tileLength);
            AscendC::Mul(zLocal, zLocal, uLocal, this->tileLength);
            AscendC::Muls(zLocal, zLocal,  1.0f / static_cast<float>(this->totalLength), this->tileLength);
        }

        outQueueZ.EnQue<float>(zLocal);
        outQueueS.EnQue<float>(sLocal);
        inQueueX.FreeTensor(xLocal);
        inQueueY.FreeTensor(yLocal);
        inQueueX.FreeTensor(uLocal);
        
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {   
        if(reduction==0){
        AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
        AscendC::LocalTensor<float> sLocal = outQueueS.DeQue<float>();
        AscendC::DataCopy(zGm[progress * this->tileLength], zLocal, this->tileLength);
        AscendC::DataCopy(sGm, sLocal, this->tileLength);
        outQueueS.FreeTensor(sLocal);
        outQueueZ.FreeTensor(zLocal);
        }else if(reduction == 1){
        AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
        AscendC::LocalTensor<float> sLocal = outQueueS.DeQue<float>();
        AscendC::DataCopy(zGm[progress * this->tileLength], zLocal, this->tileLength);
        if(progress == this->tileNum * BUFFER_NUM - 1){
            AscendC::SetAtomicAdd<float>();
            AscendC::DataCopy(sGm, sLocal, this->tileLength);
            AscendC::SetAtomicNone();
        }
            outQueueS.FreeTensor(sLocal);
            outQueueZ.FreeTensor(zLocal);
        }else if(reduction ==2){
            AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
            AscendC::LocalTensor<float> sLocal = outQueueS.DeQue<float>();
            AscendC::DataCopy(zGm[progress * this->tileLength], zLocal, this->tileLength);
            if(progress == this->tileNum * BUFFER_NUM - 1){
                AscendC::SetAtomicAdd<float>();
                AscendC::DataCopy(sGm, sLocal, this->tileLength);
                AscendC::SetAtomicNone();
            }
            outQueueS.FreeTensor(sLocal);
            outQueueZ.FreeTensor(zLocal);
        }
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX, inQueueY,inQueueS,inQueueU;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ,outQueueS;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf0;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf1;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf2;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf3;
    AscendC::GlobalTensor<float> xGm;
    AscendC::GlobalTensor<float> yGm;
    AscendC::GlobalTensor<float> zGm;
    AscendC::GlobalTensor<float> sGm;
    AscendC::GlobalTensor<float> uGm;
    uint32_t blockLength;
    uint32_t tileNum;
    uint32_t tileLength;
    uint32_t reduction;
    int32_t totalLength;
    float sum;
};

extern "C" __global__ __aicore__ void l1lossgrad_custom(GM_ADDR x, GM_ADDR y, GM_ADDR z,GM_ADDR s,GM_ADDR u,uint32_t reduction,L1LossGradCustomTilingData tiling)
{
    KernelL1LossGrad op;
    op.Init(x, y, z, s, u, reduction,tiling.totalLength, tiling.tileNum);
    op.Process();
}

